package com.jt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 重构CacheManager对象,其目的是改变AOP方式应用redis的序列化和反序列化的方式.
 */
@Configuration
public class CacheManagerConfig {
    /**
     * 重构CacheManager对象
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //定义RedisCache配置
        RedisCacheConfiguration cacheConfig=
                RedisCacheConfiguration.defaultCacheConfig()
                        //定义key的序列化方式
                        .serializeKeysWith(
                                RedisSerializationContext.
                                        SerializationPair.fromSerializer(RedisSerializer.string()))
                        //定义value的序列化方式
                        .serializeValuesWith(
                                RedisSerializationContext.
                                        SerializationPair.fromSerializer(RedisSerializer.json()));

        return  RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(cacheConfig)
                .build();//建造者模式(复杂对象的创建,建议使用这种方式,封装了对象的创建细节)
    }
}